package com.ruoyi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jnxx.task.domain.OkrStaff;
import com.jnxx.task.mapper.OkrStaffMapper;
import com.jnxx.task.tools.SendToOKR;
import com.jnxx.task.vo.OKRRequestParamsVo;
import com.jnxx.task.vo.TextCardVo;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.domain.*;
import com.ruoyi.mapper.*;
import com.ruoyi.pojo.dto.*;
import com.ruoyi.pojo.response.AdminApprovalResp;
import com.ruoyi.pojo.response.UserApprovalResp;
import com.ruoyi.service.ITRequestFormService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 申请表Service业务层处理
 * 
 * @author mzr
 * @date 2023-12-11
 */
@Service
@Slf4j
public class TRequestFormServiceImpl implements ITRequestFormService 
{
    @Autowired
    private TRequestFormMapper tRequestFormMapper;
    @Autowired
    private TFlowPathMapper tFlowPathMapper;
    @Autowired
    private TPathApproverMapper tPathApproverMapper;
    @Autowired
    private TDataInfoMapper dataInfoMapper;
    @Autowired
    private TCopyRecordMapper copyRecordMapper;
    @Autowired
    private SendToOKR sendToOKRTool;
    @Autowired
    private OkrStaffMapper okrStaffMapper;

    @Autowired
    private OkrStaffMapper staffMapper;

    /**
     * 查询申请表 operation  copy
     * 
     * @param id 申请表主键
     * @return 申请表
     */
    @Override
    public TRequestForm selectTRequestFormById(Long id)
    {
        return tRequestFormMapper.selectTRequestFormById(id);
    }

    /**
     * 查询申请表列表
     * 
     * @param tRequestForm 申请表
     * @return 申请表
     */
    @Override
    public List<TRequestForm> selectTRequestFormList(TRequestForm tRequestForm)
    {

        List<TRequestForm> requestForms = tRequestFormMapper.selectTRequestFormList(tRequestForm);
        return requestForms;
    }

    /**
     * 新增申请表
     * 
     * @param tRequestForm 申请表
     * @return 结果
     */
    @Override
    public int insertTRequestForm(TRequestForm tRequestForm)
    {
        return tRequestFormMapper.insertTRequestForm(tRequestForm);
    }

    /**
     * 修改申请表
     * 
     * @param tRequestForm 申请表
     * @return 结果
     */
    @Override
    public int updateTRequestForm(TRequestForm tRequestForm)
    {
        return tRequestFormMapper.updateTRequestForm(tRequestForm);
    }

    /**
     * 批量删除申请表
     * 
     * @param ids 需要删除的申请表主键
     * @return 结果
     */
    @Override
    public int deleteTRequestFormByIds(Long[] ids)
    {
        return tRequestFormMapper.deleteTRequestFormByIds(ids);
    }

    /**
     * 删除申请表信息
     *
     * @param id 申请表主键
     * @return 结果
     */
    @Override
    public int deleteTRequestFormById(Long id)
    {
        return tRequestFormMapper.deleteTRequestFormById(id);
    }


    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED ,rollbackFor = Exception.class)
    public boolean  pushApproval(FromDto fromDto,Long userId) {

        OkrStaff staff = okrStaffMapper.findOne(userId);
        if (staff == null){
            throw new GlobalException("账号异常，请更换账号提交！");
        }
        if (staff.getPhone()==null||staff.getPhone().isEmpty()){
            throw new GlobalException("该账号未绑定手机，请更换账号或绑定手机再提交！");
        }
        TRequestForm tRequestForm = new TRequestForm();
        TFlowPath tFlowPath = new TFlowPath();
        List<TemplateInfoDto> templateInfo = fromDto.getTemplateInfo();
        ProcessDetail processDetail = fromDto.getProcessDetail();
        List<Map<String, String>> approvers = processDetail.getApprover();
        /*基础表单*/
        if (fromDto.getType()==2){
            tRequestForm.setFromType(2);
        }else if (fromDto.getType()==3) {
            tRequestForm.setFromType(3);
        }else{
            tRequestForm.setFromType(1);
        }
        tRequestForm.setCreatTime(new Date());
        tRequestForm.setName(fromDto.getName());
        tRequestForm.setStatus(0);
        tRequestForm.setApprovalDraTimes(0);
        int num = countApproverGroups(approvers);
        tRequestForm.setApprovalTimes(num);
        tRequestForm.setPetitionerId(userId);
        tRequestFormMapper.insertTRequestForm(tRequestForm);

        /*审批流程详情*/
        tFlowPath.setCreatTime(new Date());
        tFlowPath.setFromId(tRequestForm.getId());
        tFlowPath.setMakeUser(processDetail.getMakeUser());//抄送人id  1,2
        tFlowPathMapper.insertTFlowPath(tFlowPath);


        approvers.forEach(a->{
            /*保存审批流程*/
            TPathApprover tPathApprover = new TPathApprover();
            tPathApprover.setPathId(tFlowPath.getId());
            tPathApprover.setApproverId(Long.valueOf(a.get("approver_id").toString()));
            tPathApprover.setPriority(Integer.valueOf(a.get("priority").toString()));
            tPathApprover.setStatus(0);
            tPathApproverMapper.insertTPathApprover(tPathApprover);
        });
        /*保存数据明细*/
        templateInfo.forEach(t->{
            TDataInfo tDataInfo = new TDataInfo();
            tDataInfo.setFormId(tRequestForm.getId());
            tDataInfo.setDataAttribution(t.getDataAttribution());
            tDataInfo.setDataContent(t.getDataContent());
            tDataInfo.setIdentification(t.getIdentification());
            tDataInfo.setPriority(t.getPriority());
            dataInfoMapper.insertTDataInfo(tDataInfo);
        });
        List<Integer> userIds = getUserIds(approvers);
        //发送请求审批okr消息
        HashMap<String, String> map = new HashMap<>();
        String descript = "<div class=\"gray\">%s</div> <div class=\"normal\">您有新的审批等待处理</div><div class=\"highlight\"></div>";
        StringBuilder stringBuilder = new StringBuilder();

        List<OkrStaff> byIds = okrStaffMapper.findByIds(userIds);
        for (OkrStaff byId : byIds) {
            stringBuilder.append(byId.getUserId()).append("|");
        }
        if (stringBuilder.length()>0){
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
        map.put("descript",descript);
        map.put("touser",stringBuilder.toString());
        TextCardVo textCardVo = new TextCardVo();
        OKRRequestParamsVo paramsVo = new OKRRequestParamsVo();
        textCardVo.setUrl("qy.llczy.com/#/pages/examine/approvalPage?fromId="+tRequestForm.getId());
        textCardVo.setBtntxt("查看详情");
        textCardVo.setTitle("审批单推送通知");
        paramsVo.setEnable_duplicate_check("0");
        paramsVo.setAgentid("1000033");
        paramsVo.setEnable_id_trans("0");
        paramsVo.setMsgtype("textcard");
        String resp = sendToOKRTool.sendMessage(map, paramsVo, textCardVo);
        log.info("审批单推送状态"+resp);
        return true;
    }
    /*审批通过   chUpsAdPa*/
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED ,rollbackFor = Exception.class)
    public boolean approveApproval(String auditRemark,Long fromId, Long userId, String files) {
        //查询申请表明细 - 保存审批记录 - 添加审批次数
        TRequestForm tRequestForm = tRequestFormMapper.selectTRequestFormById(fromId);
        if(tRequestForm.getStatus().equals(4) ){
            throw new GlobalException("该申请已被撤回");
        }
        if(tRequestForm.getStatus().equals(3) || tRequestForm.getStatus().equals(1)){
           throw new GlobalException("请勿重复处理");
        }
       TPathApprover tPathApprover = tPathApproverMapper.loadByFromAndApproId(fromId,userId);
        if (tPathApprover == null) {
            throw new GlobalException("无审核权限");
        }
        if (tPathApprover.getStatus().equals(1)||tPathApprover.getStatus().equals(2)){
            throw new GlobalException("请勿重复处理");
        }
        List<TPathApprover> pathApprovers = tPathApproverMapper.loadByFromId(fromId);
        ArrayList<TPathApprover> tPathApprovers = new ArrayList<>();
        pathApprovers.forEach(p->{
            if (p.getPriority().equals(tPathApprover.getPriority()) && !p.getId().equals(tPathApprover.getId())){
                if (p.getStatus().equals(1)||p.getStatus().equals(2)){
                    throw new GlobalException("该申请单已由其他管理员处理");
                }
                p.setStatus(3);
                tPathApprovers.add(p);
            }
            if(p.getPriority()<tPathApprover.getPriority()&&p.getStatus().equals(0)){
                throw new GlobalException("请在上级管理员处理完成后执行处理！");
            }
        });
        //还未审核 - 通过审核 - 修改状态  - 修改申请单状态 -如果是最后一次审核修改状态-处理关键数据，扣款或加款
        tPathApprover.setStatus(1);
        Integer approvalDraTimes = tRequestForm.getApprovalDraTimes();
        if (tRequestForm.getApprovalTimes()-approvalDraTimes==1){
            tRequestForm.setStatus(1);
            //保存抄送单
            TFlowPath flowPath = tFlowPathMapper.loadByFromId(fromId);
            TCopyRecord tCopyRecord = new TCopyRecord();
            tCopyRecord.setFromId(fromId);
            tCopyRecord.setCreatTime(new Date());
            tCopyRecord.setMakeStatus(2);
            String makeUser = flowPath.getMakeUser();
            if(makeUser!=null && !makeUser.isEmpty()){
                tCopyRecord.setMakeUser(makeUser+","+tRequestForm.getPetitionerId());
            }else {
                tCopyRecord.setMakeUser(tRequestForm.getPetitionerId().toString());
            }
            copyRecordMapper.insertTCopyRecord(tCopyRecord);
        }else {
            tRequestForm.setStatus(2);
            //发送请求审批okr消息给其他管理员
            HashMap<String, String> map = new HashMap<>();
            String descript = "<div class=\"gray\">%s</div> <div class=\"normal\">您有新的审批等待处理</div><div class=\"highlight\">"+tRequestForm.getName()+"</div>";
            StringBuilder stringBuilder = new StringBuilder();
            //查询要发送的管理员id
            List<TPathApprover> higherPriorityPathApprovers = pathApprovers.stream()
                    .filter(approver -> approver.getPriority() > tPathApprover.getPriority())
                    .collect(Collectors.toList());
            ArrayList<Integer> integers = new ArrayList<>();
            higherPriorityPathApprovers.forEach(h->{
                integers.add(h.getApproverId().intValue());
            });
            List<OkrStaff> byIds = okrStaffMapper.findByIds(integers);
            byIds.forEach(b->{
                stringBuilder.append(b.getUserId()).append("|");
            });
            if (stringBuilder.length()>0){
                stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            }
            map.put("descript",descript);
            map.put("touser",stringBuilder.toString());
            TextCardVo textCardVo = new TextCardVo();
            OKRRequestParamsVo paramsVo = new OKRRequestParamsVo();
            textCardVo.setUrl("qy.llczy.com/#/pages/examine/approvalPage?fromId="+tRequestForm.getId());
            textCardVo.setBtntxt("查看详情");
            textCardVo.setTitle("审批单推送通知");
            paramsVo.setEnable_duplicate_check("0");
            paramsVo.setAgentid("1000033");
            paramsVo.setEnable_id_trans("0");
            paramsVo.setMsgtype("textcard");
            String resp = sendToOKRTool.sendMessage(map, paramsVo, textCardVo);
            log.info("审批单推送状态"+resp);
        }
        if (auditRemark!=null&&!auditRemark.isEmpty()){
            String auditRemarkDB = tRequestForm.getAuditRemark();
            if (auditRemarkDB==null || auditRemarkDB.isEmpty()){
                tRequestForm.setAuditRemark(auditRemark);
            }else {
                tRequestForm.setAuditRemark(auditRemarkDB+"/"+auditRemark);//审核备注
            }
        }
        if (files!=null && !files.isEmpty()){
            String fileInfo = tRequestForm.getFileInfo();
            if(fileInfo==null||fileInfo.isEmpty()){
                tRequestForm.setFileInfo(files);
            }else {
                tRequestForm.setFileInfo(fileInfo+","+files);
            }
        }
        tRequestForm.setChangeTime(new Date());
        tRequestForm.setApprovalDraTimes(approvalDraTimes+1);
        tRequestFormMapper.updateTRequestForm(tRequestForm);
        tPathApprovers.add(tPathApprover);
        for (TPathApprover pathApprover : tPathApprovers) {
            tPathApproverMapper.updateTPathApprover(pathApprover);
        }
        return true;
    }

    /*查询单个申请单*/
    @Override
    public ApprovalDto queryApproval(Long fromId) {
        List<TDataInfo> tDataInfos = dataInfoMapper.loadByFromId(fromId);
        if (tDataInfos.size() == 0){
            throw new GlobalException("未查询到该申请单");
        }
        tDataInfos.sort((tDataInfo1, tDataInfo2) -> Integer.compare(tDataInfo1.getPriority(), tDataInfo2.getPriority()));
        //排序后返回
        TRequestForm tRequestForm = tRequestFormMapper.selectTRequestFormById(fromId);
        List<TPathApprover> tPathApprovers = tPathApproverMapper.loadByFromId(fromId);
        //查出每个人的名字和头像

        OkrStaff user = okrStaffMapper.findOne(tRequestForm.getPetitionerId());
        TFlowPath flowPath = tFlowPathMapper.loadByFromId(fromId);
        String makeUser = flowPath.getMakeUser();
        List<Integer> idList = getIdList(makeUser);
        List<OkrStaff> staffs = okrStaffMapper.findByIds(idList);
        ApprovalDto approvalDto = new ApprovalDto();
        ArrayList<ApproverUserDto> approverUserDtos = new ArrayList<>();
        /*审批人员详情*/
        tPathApprovers.forEach(p->{
            ApproverUserDto approverUserDto = new ApproverUserDto();
            OkrStaff admin = okrStaffMapper.findOne(p.getApproverId());
            approverUserDto.setAssessorName(admin.getName());
            approverUserDto.setAssPortrait(admin.getAvatar());
            approverUserDto.setPriority(p.getPriority());
            approverUserDto.setAssStatus(p.getStatus());
            approverUserDtos.add(approverUserDto);
        });
        Map<Integer, List<ApproverUserDto>> priorityToApprovers = approverUserDtos.stream()
                .collect(Collectors.groupingBy(ApproverUserDto::getPriority));
        ArrayList<ApproverUserListDto> approverUserListDtos = new ArrayList<>();
        for (Integer priority : new TreeSet<>(priorityToApprovers.keySet())) {
            ApproverUserListDto approverUserListDto = new ApproverUserListDto();
            approverUserListDto.setApproverUserDtos(priorityToApprovers.get(priority));
            approverUserListDtos.add(approverUserListDto);
        }
        approvalDto.setPathApprovers(approverUserListDtos);
        approvalDto.setFromStatus(tRequestForm.getStatus());
        approvalDto.setTDataInfos(tDataInfos);
        approvalDto.setFromName(tRequestForm.getName());
        approvalDto.setImageUsername(user.getAvatar());
        approvalDto.setUsername(user.getName());
        approvalDto.setRevocationRemark(tRequestForm.getRevocationRemark());//撤回原因
        approvalDto.setTurnDownRemark(tRequestForm.getRejectRemark());
        approvalDto.setAuditRemark(tRequestForm.getAuditRemark());
        approvalDto.setFileUrls(tRequestForm.getFileInfo());

        //approvalDto.setPathApprovers(tPathApprovers);
        ArrayList<CopyUserDto> copyUsers = new ArrayList<>();
        staffs.forEach(s->{
            CopyUserDto copyUserDto = new CopyUserDto();
            copyUserDto.setUsername(s.getName());
            copyUserDto.setCopyPortrait(s.getAvatar());
            copyUsers.add(copyUserDto);
        });
        approvalDto.setCopyUsers(copyUsers);

        return approvalDto;
    }

    /**
     * 查询申请表的抄送人以及审批人
     * @param fromId
     * @return
     */
    @Override
    public ApprovalDto selectAllUser(Long fromId) {
        // 查询抄送人
        String idsStr = tRequestFormMapper.selectCopyUserById(fromId);
        String[] ids = idsStr.split(",");
        List<Long> longList = Arrays.stream(ids)
                .map(Long::parseLong)
                .collect(Collectors.toList());
        String[] names = staffMapper.findNameByIds(longList);
        String userNames = String.join("，", names);
        ApprovalDto approvalDto = new ApprovalDto();
        approvalDto.setCopyUsername(userNames);

        // 查询审批人
        List<Long> userByIds = tRequestFormMapper.selectApprovalNameById(fromId);
        String[] approvalNameStr = staffMapper.findNameByIds(userByIds);
        String approvalNames = String.join("，", approvalNameStr);
        approvalDto.setApprovalUsername(approvalNames);
        return approvalDto;
    }

    /*查询管理员审核与否记录*/
    @Override
    public List<AdminApprovalResp> queryApprovalRecord(String keyword,Long userId,int statusO,int statusT,String startTimeStr,String endTimeStr) {
        LocalDateTime startTime;
        LocalDateTime endTime;

        if (endTimeStr!=null && !endTimeStr.isEmpty()){
            endTime=LocalDateTime.parse(endTimeStr.split("T")[0]+"T23:59:59").plusDays(1);
        }else {
            endTime = LocalDateTime.now();
        }
        if (startTimeStr!=null && !startTimeStr.isEmpty()){
            startTime=LocalDateTime.parse(startTimeStr.split("T")[0]+"T00:00:00").plusDays(1);
        }else {
            startTime = endTime.minusWeeks(1);
        }

        List<AdminApprovalResp> adminApprovalResps = tRequestFormMapper.loadByUserIdAndStatus(userId,statusO,statusT,startTime,endTime);
        List<AdminApprovalResp> filteredResps = new ArrayList<>();
        // 遍历查询结果并检查phraseStr是否包含关键字
        if (keyword!=null&&!keyword.isEmpty()){
            for (AdminApprovalResp adminApprovalResp : adminApprovalResps) {
                String phraseStr = adminApprovalResp.getPhraseStr();
                if (phraseStr != null && (phraseStr.contains(keyword)||adminApprovalResp.getUsername().contains(keyword))) {
                    // 如果包含关键字，则添加到新列表中
                    filteredResps.add(adminApprovalResp);
                }
            }
            // 返回过滤后的列表
            return filteredResps;
        }else {
            return adminApprovalResps;
        }
    }

    /*查询管理员抄送记录*/
    @Override
    public List<AdminApprovalResp> queryApprovalCopyRecord(String keyword,Long userId,String startTimeStr,String endTimeStr) {
        //查询抄送记录 times
        LocalDateTime startTime;
        LocalDateTime endTime;

        if (endTimeStr!=null && !endTimeStr.isEmpty()){
            endTime=LocalDateTime.parse(endTimeStr.split("T")[0]+"T23:59:59").plusDays(1);
        }else {
            endTime = LocalDateTime.now();
        }
        if (startTimeStr!=null && !startTimeStr.isEmpty()){
            startTime=LocalDateTime.parse(startTimeStr.split("T")[0]+"T00:00:00").plusDays(1);
        }else {
            startTime = endTime.minusWeeks(1);
        }


        List<AdminApprovalResp>  AdminApprovalRespList = tFlowPathMapper.loadCopyRecord(userId,startTime,endTime);
        List<AdminApprovalResp> filteredResps = new ArrayList<>();
        if (keyword!=null&&!keyword.isEmpty()){
            for (AdminApprovalResp adminApprovalResp : AdminApprovalRespList) {
                String phraseStr = adminApprovalResp.getPhraseStr();
                if (phraseStr != null && (phraseStr.contains(keyword)||adminApprovalResp.getUsername().contains(keyword))) {
                    // 如果包含关键字，则添加到新列表中
                    filteredResps.add(adminApprovalResp);
                }
            }
            // 返回过滤后的列表
            return filteredResps;
        }else {
            return AdminApprovalRespList;
        }
    }

    /*查询用户提交的所有审批*/
    @Override
    public List<UserApprovalResp> queryUserApprovalRecord(String keyword, Long userId,String formName, String startTimeStr,String endTimeStr ) {

        LocalDateTime startTime;
        LocalDateTime endTime;

        if (endTimeStr!=null && !endTimeStr.isEmpty()){
            endTime=LocalDateTime.parse(endTimeStr.split("T")[0]+"T23:59:59").plusDays(1);
        }else {
            endTime = LocalDateTime.now();
        }
        if (startTimeStr!=null && !startTimeStr.isEmpty()){
            startTime=LocalDateTime.parse(startTimeStr.split("T")[0]+"T00:00:00").plusDays(1);
        }else {
            startTime = endTime.minusWeeks(1);
        }

        List<UserApprovalResp> userApprovalResponses = tRequestFormMapper.loadUserApprovalRecordAll(userId,formName,startTime,endTime);
        List<UserApprovalResp> filteredResps = new ArrayList<>();
        if (keyword!=null&&!keyword.isEmpty()){
            for (UserApprovalResp userApprovalResp : userApprovalResponses) {
                String phraseStr = userApprovalResp.getPhraseStr();
                if (phraseStr != null && (phraseStr.contains(keyword)||userApprovalResp.getFromName().contains(keyword))) {
                    // 如果包含关键字，则添加到新列表中
                    filteredResps.add(userApprovalResp);
                }
            }
            // 返回过滤后的列表
            return filteredResps;
        }else {
            return userApprovalResponses;
        }
    }


    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED ,rollbackFor = Exception.class)
    public boolean pushApprovalAgain(PushApprovalAgainDto data, Long userId) {
        Long fromId = data.getFromId();
        List<TemplateInfoDto> templateInfo = data.getTemplateInfo();
        //查出path抄送人
        //查出path_app 审核人
        //请求头获取提单人
        OkrStaff staff = okrStaffMapper.findOne(userId);
        if (staff == null){
            throw new GlobalException("账号异常，请更换账号提交！");
        }
        if (staff.getPhone()==null||staff.getPhone().isEmpty()){
            throw new GlobalException("该账号未绑定手机，请更换账号或绑定手机再提交！");
        }
        TFlowPath flowPath = tFlowPathMapper.loadByFromId(fromId);
        if (flowPath==null){
            throw new GlobalException("申请提交失败，建议回到首页提交！");
        }
        String makeUser = flowPath.getMakeUser();//抄送人
        TRequestForm requestForm = tRequestFormMapper.selectTRequestFormById(fromId);

        TRequestForm tRequestForm = new TRequestForm();
        tRequestForm.setName(requestForm.getName());
        tRequestForm.setPetitionerId(userId);
        tRequestForm.setStatus(0);
        tRequestForm.setCreatTime(new Date());
        tRequestForm.setApprovalDraTimes(0);
        tRequestForm.setApprovalTimes(requestForm.getApprovalTimes());
        tRequestFormMapper.insertTRequestForm(tRequestForm);

        TFlowPath tFlowPath = new TFlowPath();
        tFlowPath.setCreatTime(new Date());
        tFlowPath.setFromId(tRequestForm.getId());
        tFlowPath.setMakeUser(makeUser);//抄送人id  1,2
        tFlowPathMapper.insertTFlowPath(tFlowPath);


        List<TPathApprover> tPathApprovers = tPathApproverMapper.loadByFromId(fromId);
        if (tPathApprovers.size()<1){
            throw new GlobalException("申请提交失败，建议回到首页提交！");
        }

        tPathApprovers.forEach(a->{
            /*保存审批流程*/
            TPathApprover tPathApprover = new TPathApprover();
            tPathApprover.setPathId(tFlowPath.getId());
            tPathApprover.setApproverId(a.getApproverId());
            tPathApprover.setPriority(a.getPriority());
            tPathApprover.setStatus(0);
            tPathApproverMapper.insertTPathApprover(tPathApprover);
        });

        /*保存数据明细*/
        templateInfo.forEach(t->{
            TDataInfo tDataInfo = new TDataInfo();
            tDataInfo.setFormId(tRequestForm.getId());
            tDataInfo.setDataAttribution(t.getDataAttribution());
            tDataInfo.setDataContent(t.getDataContent());
            tDataInfo.setIdentification(t.getIdentification());
            tDataInfo.setPriority(t.getPriority());
            dataInfoMapper.insertTDataInfo(tDataInfo);
        });
        HashMap<String, String> map = new HashMap<>();
        String descript = "<div class=\"gray\">%s</div> <div class=\"normal\">您有新的审批等待处理</div><div class=\"highlight\"></div>";
        StringBuilder stringBuilder = new StringBuilder();
        List<Integer> ids = getUserIdsForObject(tPathApprovers);

        List<OkrStaff> byIds = okrStaffMapper.findByIds(ids);
        for (OkrStaff byId : byIds) {
            stringBuilder.append(byId.getUserId()).append("|");
        }
        if (stringBuilder.length()>0){
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
        map.put("descript",descript);
        map.put("touser",stringBuilder.toString());
        TextCardVo textCardVo = new TextCardVo();
        OKRRequestParamsVo paramsVo = new OKRRequestParamsVo();
        textCardVo.setUrl("qy.llczy.com/#/pages/examine/approvalPage?fromId="+tRequestForm.getId());
        textCardVo.setBtntxt("查看详情");
        textCardVo.setTitle("审批单推送通知");
        paramsVo.setEnable_duplicate_check("0");
        paramsVo.setAgentid("1000033");
        paramsVo.setEnable_id_trans("0");
        paramsVo.setMsgtype("textcard");
        String resp = sendToOKRTool.sendMessage(map, paramsVo, textCardVo);
        log.info("审批单推送状态"+resp);
        return true;
    }

    /*审批驳回*/
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED ,rollbackFor = Exception.class)
    public boolean rejectApproval(HashMap<String,Object> rejectDto, Long userId) {
        Long fromId = Long.valueOf(String.valueOf(rejectDto.get("FromId")));
        String rejectRemark = String.valueOf(rejectDto.get("rejectRemark"));

        TRequestForm tRequestForm = tRequestFormMapper.selectTRequestFormById(fromId);
        if (tRequestForm.getStatus().equals(4)) {
            throw new GlobalException("该申请已被撤回");
        }

        if (tRequestForm.getStatus().equals(3) || tRequestForm.getStatus().equals(1) ) {
            throw new GlobalException("请勿重复处理");
        }
        tRequestForm.setRejectRemark(rejectRemark);
        List<TPathApprover> tPathApprovers = tPathApproverMapper.loadByFromId(fromId);
        TPathApprover tPathApprover = tPathApproverMapper.loadByFromAndApproId(fromId, userId);
        if (tPathApprover == null) {//
            throw new GlobalException("无审核权限");
        }
        if (tPathApprover.getStatus().equals(1)||tPathApprover.getStatus().equals(2)){
            throw new GlobalException("请勿重复处理");
        }
        ArrayList<TPathApprover> tPathApproversData = new ArrayList<>();
        tPathApprovers.forEach(p->{
            if (p.getPriority().equals(tPathApprover.getPriority()) && !p.getId().equals(tPathApprover.getId())){
                if (p.getStatus().equals(1)||p.getStatus().equals(2)){
                    throw new GlobalException("该申请单已由其他管理员处理");
                }
                p.setStatus(4);
                tPathApproversData.add(p);
            }
            if (p.getPriority()<tPathApprover.getPriority()&&p.getStatus().equals(0)){
                throw new GlobalException("请在上级管理员处理完成后执行处理!");
            }
            if (tPathApprover.getPriority()<p.getPriority()){
                p.setStatus(4);
                tPathApproversData.add(p);
            }

        });
        //还未审核 - 驳回审核，保存驳回备注
        tRequestForm.setChangeTime(new Date());
        tRequestForm.setStatus(3);
        tRequestForm.setRejectRemark(rejectRemark);
        tPathApprover.setStatus(2);//驳回
        tPathApproversData.add(tPathApprover);
        for (TPathApprover tPathApproversDatum : tPathApproversData) {
            tPathApproverMapper.updateTPathApprover(tPathApproversDatum);
        }
        tRequestFormMapper.updateTRequestForm(tRequestForm);

        Long petitionerId = tRequestForm.getPetitionerId();//申请人 id
        OkrStaff staff = okrStaffMapper.findOne(petitionerId);
        HashMap<String, String> map = new HashMap<>();
        String descript = "<div class=\"gray\">%s</div> <div class=\"normal\">驳回原因："+rejectRemark+"</div><div class=\"highlight\"></div>";
        map.put("descript",descript);
        map.put("touser",staff.getUserId());
        TextCardVo textCardVo = new TextCardVo();
        OKRRequestParamsVo paramsVo = new OKRRequestParamsVo();
        textCardVo.setUrl("qy.llczy.com/#/pages/examine/approvalPage?fromId="+tRequestForm.getId()+"&status=1");
        textCardVo.setBtntxt("查看详情");
        textCardVo.setTitle("审批单驳回通知");
        paramsVo.setEnable_duplicate_check("0");
        paramsVo.setAgentid("1000033");
        paramsVo.setEnable_id_trans("0");
        paramsVo.setMsgtype("textcard");
        String resp = sendToOKRTool.sendMessage(map, paramsVo, textCardVo);
        log.info("审批单驳回推送状态"+resp);
        return true;
    }



    @Override
    public boolean revocationApprovalPathForm(Long userId, RevocationApprovalFormDto data) {
        //查询该审批单是否存在或是否是该用户提交的审批
        TRequestForm requestForm = tRequestFormMapper.selectTRequestFormById(data.getFromId());
        if (requestForm == null){
            throw new GlobalException("未查询到相关审批单！");
        }
        if (!requestForm.getPetitionerId().equals(userId)){
            throw new GlobalException("非提交者本人无法操作！");
        }
        /** 申请单状态  0-待审核  2-审核中    3-审核未通过 1-审核通过4 - 撤回*/
        Integer status = requestForm.getStatus();
        if (status==4){
            throw new GlobalException("重复操作！");
        }
        if (status==3){
            throw new GlobalException("该任务已被驳回，不可撤销！");
        }
        if (status==1){
            throw new GlobalException("该审批单已处理完成，不可撤销！");
        }
        //0 - 2 可操作 修改为4 撤回
        requestForm.setStatus(4);
        requestForm.setRevocationRemark(data.getRemark());
        this.updateTRequestForm(requestForm);
        //修改完 - 发送okr消息 提示到该用户撤回详情
        OkrStaff staff = okrStaffMapper.findOne(userId);
        sendRevocationMessage(requestForm,staff.getUserId());
        return true;
    }

    @Override
    public ArrayList<HashMap<String,Object>> selectTRequestFormToExport(ExportRequestFromDto exportRequestFromDto) {
        List<HashMap<String,Object>> dataMaps =
                this.tRequestFormMapper.selectTRequestFormToListInfo(exportRequestFromDto.getName(),
                exportRequestFromDto.getStatus(),exportRequestFromDto.getUserName());
        ArrayList<HashMap<String,Object>> newMaps = new ArrayList<>();
        for (HashMap<String, Object> dataMap : dataMaps) {
            String data = String.valueOf(dataMap.remove("data"));
            List<JSONObject> dataInfos = JSON.parseArray(data, JSONObject.class);
            for (JSONObject dataInfo : dataInfos) {
                for (Map.Entry<String, Object> entry : dataInfo.entrySet()) {
                    String key = entry.getKey();
                    String value = String.valueOf(entry.getValue()); // 确保值是字符串类型
                    dataMap.put(key, value);
                }
            }
            newMaps.add(dataMap);
        }
        return newMaps;
    }


    private void sendRevocationMessage(TRequestForm requestForm, String userId) {
        try {
            HashMap<String, String> successMap = new HashMap<>();
            String descriptT = "<div class=\"gray\">%s</div> <div class=\"normal\">您提交的 "+requestForm.getName()+" 已撤回,撤回原因："+requestForm.getRevocationRemark()+"</div><div class=\"highlight\"></div>";
            successMap.put("descript", descriptT);
            successMap.put("touser", userId);
            TextCardVo textCardVoT = new TextCardVo();
            OKRRequestParamsVo paramsVoT = new OKRRequestParamsVo();
            textCardVoT.setUrl("qy.llczy.com/#/pages/examine/userApproveRecored");
            textCardVoT.setBtntxt("查看详情");
            textCardVoT.setTitle("审批单撤回通知");
            paramsVoT.setEnable_duplicate_check("0");
            paramsVoT.setAgentid("1000033");
            paramsVoT.setEnable_id_trans("0");
            paramsVoT.setMsgtype("textcard");
            String res = sendToOKRTool.sendMessage(successMap, paramsVoT, textCardVoT);
            log.info("审批单撤回通知状态" + res);
        } catch (Exception e) {
            log.error("审批撤回通知方法异常" + e);
        }

    }



    public static int countApproverGroups(List<Map<String,String>> approvers) {
        Set<Integer> uniquePriorities = new HashSet<>();
        for (Map approver : approvers) {
            uniquePriorities.add(Integer.valueOf(approver.get("priority").toString()));
        }
        return uniquePriorities.size();
    }

    public static List<Integer> getUserIds(List<Map<String,String>> approvers) {

        int minPriority = Integer.MAX_VALUE; // 初始化为最大值
        List<Integer> highestPriorityApproverIds = new ArrayList<>();

        for (Map<String, String> approver : approvers) {
            int priority = Integer.parseInt(approver.get("priority"));
            if (priority < minPriority) {
                minPriority = priority;
                highestPriorityApproverIds.clear();
                highestPriorityApproverIds.add(Integer.valueOf(approver.get("approver_id")));
            } else if (priority == minPriority) {
                // 如果优先级相同，将approver_id添加到列表中
                highestPriorityApproverIds.add(Integer.valueOf(approver.get("approver_id")));
            }
        }
        if (!highestPriorityApproverIds.isEmpty()) {
            return highestPriorityApproverIds;
        } else {
            return null;
        }
    }
    public static List<Integer> getUserIdsForObject(List<TPathApprover> approvers) {

        int minPriority = Integer.MAX_VALUE; // 初始化为最大值
        List<Integer> highestPriorityApproverIds = new ArrayList<>();

        for (TPathApprover approver : approvers) {
            int priority = approver.getPriority();
            if (priority < minPriority) {
                minPriority = priority;
                highestPriorityApproverIds.clear();
                highestPriorityApproverIds.add(Integer.valueOf(String.valueOf(approver.getApproverId())));
            } else if (priority == minPriority) {
                // 如果优先级相同，将approver_id添加到列表中
                highestPriorityApproverIds.add(Integer.valueOf(String.valueOf(approver.getApproverId())));
            }
        }
        if (!highestPriorityApproverIds.isEmpty()) {
            return highestPriorityApproverIds;
        } else {
            return null;
        }
    }



    public static List<Integer> getIdList(String ids){
        String[] parts = ids.split(","); // 使用逗号分隔字符串
        List<Integer> longValues = new ArrayList<>();
        for (String part : parts) {
            part = part.trim(); // 去除字符串两端的空格
            if (!part.isEmpty()) { // 判断分割出来的字符串是否为空
                longValues.add(Integer.valueOf(part)); // 将字符串转换为long并添加到列表中
            }
        }
        return longValues;
    }




}
